import React, { useState, useEffect } from 'react';
import { Form, Row, Col, Switch, DatePicker, Button } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import moment, { Moment } from 'moment';
import { ASelect } from '@/components/SelfComp';
import { DataItem, FormProps } from '@/types/global';
import { CqDetailInfoFormValue } from '@/types/workbench';
import { formLayout, basicFormItemLayout } from '@/utils/commons';
import { transform2moment } from '@/utils/utils';

type CqDetailInfoFormProps<T> = FormProps<T> & {
  designerData: DataItem[];
  flag?: string;
}

type CqDetailInfoFormType = {
  needDesigner: boolean;
  designerA?: string;
  designerB?: string;
  devDate: Moment[];
  sitDate: Moment[];
  uatDate: Moment[];
  prdDate: Moment;
}

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormatPattern = 'YYYY-MM-DD';
const dateFormatPattern2 = 'YYYYMMDD';
const current = moment();

type DetailMoment = {
  devDate: Moment[];
  sitDate: Moment[];
  uatDate: Moment[];
  prdDate: Moment;
}

const EMPTY_MOMENT: DetailMoment = {
  devDate: [current, current],
  sitDate: [current, current],
  uatDate: [current, current],
  prdDate: current,
};

/**
 * 录入需求详细信息
 */
const CqDetailInfoForm = (props: CqDetailInfoFormProps<CqDetailInfoFormValue>) => {
  // 是否需要设计人员
  const [needDesignerFlag, setNeedDesignerFlag] = useState<boolean>(true);
  const [disabled, setDisabled] = useState<boolean>(false);
  const [form] = Form.useForm<CqDetailInfoFormType>();
  
  useEffect(() => {
    // 初始化表单数据
    const { flag } = props;
    if (flag && flag === 'view') {
      setDisabled(true);
    }
  }, []);

  /**
   * 是否需要设计人员
   * @param checked boolean型，表示是否需要设计人员，true表示需要，false表示不需要
   */
  const needDesignerChange = (checked: boolean) => {
    // 不需要，则隐藏设计人员栏位，并清空栏位值
    if (!checked) {
      setNeedDesignerFlag(false);
      form.resetFields([
        'designerA',
        'designerB'
      ]);
    }else{
      setNeedDesignerFlag(true);
    }
  }

  /**
   * 将遍历日期框中的所有日期，然后根据条件判断当前遍历的日期是否被禁用，条件判断返回true时，禁用，如果不满足条件则不禁用
   * @param currentDate Moment类型
   */
  const devDateDisable: RangePickerProps['disabledDate'] = (currentDate: Moment) => {
    // 拿到SIT日期
    // 拿到UAT日期
    // 如果SIT不为空，则可选择日期最多到SIT开始日期，
    // 如果SIT为空，UAT不为空，则可选择日期最多到UAT开始日期，
    // 如果SIT和UAT均为空，则无限制
    const sitDate: Moment[] = form.getFieldValue('sitDate');
    const uatDate: Moment[] = form.getFieldValue('uatDate');
    if (sitDate) {
      return currentDate && currentDate > sitDate[0].endOf('day');
    }
    if (uatDate) {
      return currentDate && currentDate > uatDate[0].endOf('day');
    }
    return false;
  }

  /**
   * 将遍历日期框中的所有日期，然后根据条件判断当前遍历的日期是否被禁用，条件判断返回true时，禁用，如果不满足条件则不禁用
   * @param currentDate Moment数组
   */
  const sitDateDisable = (currentDate: Moment) => {
    // 拿到DEV日期
    // 拿到UAT日期
    // 如果DEV不为空，UAT为空，则可选择日期从DEV结束日期开始，
    // 如果DEV不为空，UAT不为空，则可选择日期从DEV结束日期开始，到UAT开始日期结束
    // 如果DEV为空，UAT为空，则无限制，
    // 如果DEV为空，UAT不为空，则可选择日期到UAT开始日期结束
    const devDate: Moment[] = form.getFieldValue('devDate');
    const uatDate: Moment[] = form.getFieldValue('uatDate');
    if (devDate) {
      return currentDate && currentDate < devDate[1].endOf('day');
    }
    if (uatDate) {
      return currentDate && currentDate > uatDate[0].endOf('day');
    }
    return false;
  }

  /**
   * 将遍历日期框中的所有日期，然后根据条件判断当前遍历的日期是否被禁用，条件判断返回true时，禁用，如果不满足条件则不禁用
   * @param currentDate Moment数组
   */
  const uatDateDisable = (currentDate: Moment) => {
    // 拿到DEV日期
    // 拿到SIT日期
    // 如果SIT不为空，则可选择日期从SIT结束日期开始，
    // 如果SIT为空，DEV不为空，则可选择日期从DEV结束日期开始，
    // 如果DEV和SIT均为空，则无限制
    const devDate: Moment[] = form.getFieldValue('devDate');
    const sitDate: Moment[] = form.getFieldValue('sitDate');
    if (sitDate) {
      return currentDate && currentDate < sitDate[1].endOf('day');
    }
    if (devDate) {
      return currentDate && currentDate < devDate[1].endOf('day');
    }
    return false;
  }

  /**
   * 表单提交
   */
  const handleSubmit = () => {
    // 收集表单数据
    // 传递回父组件
    const fieldsValue = form.getFieldsValue();
    console.info(fieldsValue);
    const { needDesigner, devDate, sitDate, uatDate, prdDate: prdDateMoment, ...rest } = fieldsValue;
    const values = {
      devStartDate: devDate[0].format(dateFormatPattern),
      devEndDate: devDate[1].format(dateFormatPattern),
      sitStartDate: sitDate[0].format(dateFormatPattern),
      sitEndDate: sitDate[1].format(dateFormatPattern),
      uatStartDate: uatDate[0].format(dateFormatPattern),
      uatEndDate: uatDate[1].format(dateFormatPattern),
      prdDate: prdDateMoment.format(dateFormatPattern),
      ...rest
    };
    console.log('Received values of form: ', values);
    const { onSubmit } = props;
    if (onSubmit) {
      onSubmit({
        ...values
      });
    }
  }

  const handleQuit = () => {
    // 先清除form表单
    form.resetFields();
    const { onCancel } = props;
    if (onCancel) {
      onCancel();
    }
  }

  const { colon, loading, formData, designerData } = props;
  const { cqCode } = formData;
  // 8-8布局
  const formItemLayout = basicFormItemLayout;
  // console.log(needDesignerFlag, disabled, formData);
  let detailMoment: DetailMoment = EMPTY_MOMENT;
  if (disabled) {
    const devStart = transform2moment(formData.devStartDate, dateFormatPattern2);
    const devEnd = transform2moment(formData.devEndDate, dateFormatPattern2);
    const sitStart = transform2moment(formData.sitStartDate, dateFormatPattern2);
    const sitEnd = transform2moment(formData.sitEndDate, dateFormatPattern2);
    const uatStart = transform2moment(formData.uatStartDate, dateFormatPattern2);
    const uatEnd = transform2moment(formData.uatEndDate, dateFormatPattern2);
    const prdDate = transform2moment(formData.prdDate, dateFormatPattern2);
    detailMoment = {
      devDate: [devStart, devEnd],
      sitDate: [sitStart, sitEnd],
      uatDate: [uatStart, uatEnd],
      prdDate,
    };
  }

  return(
    <React.Fragment>
      {cqCode &&
      <Form layout={formLayout}
        form={form}
        onFinish={handleSubmit}
      >
        <Row>
          <Col span={12}>
            <FormItem label='是否需要设计人员' name='needDesigner' {...formItemLayout} colon={colon} valuePropName='checked'
              initialValue={needDesignerFlag}
            >
              <Switch checkedChildren='需要' unCheckedChildren='不需要' onChange={needDesignerChange} disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
        {
          !needDesignerFlag ? null :
          <Row>
            <Col span={12}>
              <FormItem label='设计人A' name='designerA' {...formItemLayout} colon={colon}
                rules={[
                  { required: true, message: '设计人A必输' },
                ]}
                initialValue={formData.designerA}
              >
                <ASelect dataSource={designerData} disabled={disabled} />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label='设计人B' name='designerB' {...formItemLayout} colon={colon}
                initialValue={formData.designerB}
              >
                <ASelect dataSource={designerData} disabled={disabled} />
              </FormItem>
            </Col>
          </Row>
        }
        <Row>
          <Col span={12}>
            <FormItem label='DEV起止时间' name='devDate' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: 'DEV起止时间必输' },
              ]}
            >
              {
                disabled ?
                <RangePicker format={dateFormatPattern} defaultValue={[detailMoment.devDate[0], detailMoment.devDate[1]]} disabled={[disabled, disabled]} />
                :
                <RangePicker format={dateFormatPattern} disabledDate={devDateDisable} />
              }
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='SIT起止时间' name='sitDate' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: 'SIT起止时间必输' },
              ]}
            >
              {
                disabled ?
                <RangePicker format={dateFormatPattern} defaultValue={[detailMoment.sitDate[0], detailMoment.sitDate[1]]} disabled={[disabled, disabled]} />
                :
                <RangePicker format={dateFormatPattern} disabledDate={sitDateDisable} />
              }
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='UAT起止时间' name='uatDate' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: 'UAT起止时间必输' },
              ]}
            >
              {
                disabled ?
                <RangePicker format={dateFormatPattern} defaultValue={[detailMoment.uatDate[0], detailMoment.uatDate[1]]} disabled={[disabled, disabled]} />
                :
                <RangePicker format={dateFormatPattern} disabledDate={uatDateDisable} />
              }
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='投产日期' name='prdDate' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '投产日期必输' },
              ]}
            >
              {
                disabled ?
                <DatePicker format={dateFormatPattern} defaultValue={detailMoment.prdDate} style={{ width: '100%' }} disabled={disabled} />
                :
                <DatePicker format={dateFormatPattern} style={{ width: '100%' }} />
              }
            </FormItem>
          </Col>
        </Row>
        {
          disabled ? null:
          <Row justify='center'>
            <Col>
              <FormItem>
                <Button type='primary' loading={loading} htmlType='submit'>
                  提交
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={handleQuit}>返回</Button>
              </FormItem>
            </Col>
          </Row>
        }
      </Form>}
    </React.Fragment>
  );
}

export default CqDetailInfoForm;